<?php
/**
 * Created by PhpStorm.
 *Author:huminghui
 * User: Administrator
 * Date: 2020/4/18
 * Time: 10:00
 */

namespace app\admin\model;


use think\Model;

class AuthRule extends Model
{
    /*
 * 读取所有数据
 */
    public function selectData(){
        $result=$this->select()->toArray();
        return $this->sort($result);
    }
    /*
     * 所有数据排序
     */
    public function sort($data,$pid=0,$level=0){
        static $arr=array();
        foreach($data as $k=>$v){
            if($v['pid']==$pid){
                $v['level'] = $level;
                $arr[] = $v;
                $this->sort($data,$v['id'],$level+1);
            }
        }
        return $arr;
    }
    /*
   * 保存数据
   */
    public function saveData($data){
        $data['create_time']=date('Y-m-d H:i:s',time());
        return $this->save($data);
    }

    /*
  * 更新数据
  */
    public function updateData($data){
        $data['update_time']=date('Y-m-d H:i:s',time());
        $result = $this->update($data);
        return $result;

    }
    /*
* 根据id查询数据
*/
    public function readDataById($data){
        return $this->where($data)->find()->toArray();
    }
    /*
     * 根据id删除数据
     */
    public function delDataById($data){
        $allData=$this->select()->toArray();
        $childrenAuth=$this->_getChildren($allData,$data);
        //把父元素的id加进去
        array_push($childrenAuth,$data);
        $result=AuthRule::destroy($childrenAuth);
        return $result;
    }
    public function _getChildren($data,$id){
        static  $arr = [];
        foreach ($data as $key =>$val){
            if($val['pid'] == $id){
                $arr = $val['id'];
                dump($arr);die();
                $this->_getChildren($data,$val['id']);
            }
        }

        return $arr;
    }
    /*
    * 根据id删除所有数据
    */
    public function delAllData($data){
        $result = $this->where('id','in',$data)->delete();
        return $result;
    }
    /*
       * 获取ztree格式数据
       */
    public function ztreeForm(){
        $result=$this->field('id,pid,title')->select()->toArray();
        return $this->formatZtree($result);
    }
    /*
 * 格式化成ztree数据
 */
    public function formatZtree($data){
        static $arr=array();
        foreach($data as $k=>$v){
            if($v['pid']==0){
                $v['open']=true;
            }
            $v['name']=$v['title'];
            $v['pId']=$v['pid'];
            unset($v['pid']);
            unset($v['title']);
            $arr[]=$v;
        }
        return $arr;
    }
}